package com.lkd.job;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class SupplyJob {

    @Autowired
    private VendingMachineService vendingMachineService;


    /**
     * 售货机定时补货,并发送补货协议
     */
    @XxlJob("supplyJobHandler")
    public ReturnT<String> supplyJobHandler(String param) {
        //xxl-job售货机自动补货,路由策略分片广播
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        //获取总分片数
        int numbers = shardingVo.getTotal();
        //获取当前微服务的分片索引
        int index = shardingVo.getIndex();
        XxlJobLogger.log( "分片参数  当前分片索引"+index+"  总分片数"+numbers);


        //查询所有运行中的售货机
        List<VendingMachineEntity> vmList = vendingMachineService.list(Wrappers.<VendingMachineEntity>lambdaQuery()
                .eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING)
                //对id%分片总数=当前分片索引
                .apply("mod(id,"+numbers+" ) = "+index)
        );
        vmList.stream().forEach(vm -> {
            XxlJobLogger.log("扫描售货机" + vm.getInnerCode());
            vendingMachineService.sendSupplyTask(vm.getInnerCode());
        });

        return ReturnT.SUCCESS;
    }

}
